package com.gobang.controller;

import com.gobang.domain.dto.PageRequest;
import com.gobang.domain.dto.user.UserRoleUpdateRequest;
import com.gobang.domain.dto.user.UserStatusUpdateRequest;
import com.gobang.domain.vo.PageData;
import com.gobang.domain.vo.Result;
import com.gobang.domain.vo.user.UserListItemVO;
import com.gobang.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/admin/users")
@PreAuthorize("hasRole('ADMIN')")
@RequiredArgsConstructor
public class AdminUserController {

    private final UserService userService;

    @GetMapping
    public Result<PageData<UserListItemVO>> pageUsers(@Valid PageRequest pageRequest,
                                                      @RequestParam(required = false) String username,
                                                      @RequestParam(required = false) String role,
                                                      @RequestParam(required = false) Boolean enabled) {
        PageData<UserListItemVO> pageData = userService.pageUsers(pageRequest, username, role, enabled);
        return Result.success(pageData);
    }

    @PatchMapping("/{userId}/status")
    public Result<Void> updateUserStatus(@PathVariable Long userId,
                                         @Valid @RequestBody UserStatusUpdateRequest request) {
        userService.updateUserStatus(userId, request.getStatus());
        return Result.success("账号状态更新成功");
    }

    @PatchMapping("/{userId}/role")
    public Result<Void> updateUserRole(@PathVariable Long userId,
                                       @Valid @RequestBody UserRoleUpdateRequest request) {
        userService.updateUserRole(userId, request.getRole());
        return Result.success("角色更新成功");
    }
}
